package org.lionel.task;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;


public class Item<T> implements Delayed {

    /**
     * 到期时间(秒)
     */
    private long activeTime;
    /**
     * 业务数据
     */
    private T data;

    public Item(long activeTime, T data) {
        this.activeTime = activeTime * 1000 + System.currentTimeMillis();
        this.data = data;
    }

    public long getActiveTime() {
        return activeTime;
    }

    public T getData() {
        return data;
    }

    /**
     * 从这个方法返回到激活日期的剩余时间
     */
    @Override
    public long getDelay(TimeUnit unit) {
        long time = unit.convert(this.activeTime - System.currentTimeMillis(), unit);
        return time;
    }

    /**
     * Delayed接口继承了Comparable接口，按剩余时间排序，实际计算考虑精度为纳秒数
     */
    @Override
    public int compareTo(Delayed o) {
        long d = (getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
        if (d == 0) {
            return 0;
        } else {
            if (d < 0) {
                return -1;
            } else {
                return 1;
            }
        }
    }
}
